<!--音频播放器-->
<template>
  <section  ref="dialogWrap" v-if="isShow" id="videoPlayerWrap" class="audio-wrap" :class="instanceClass">

    <div class="inner" :class="audioClass">
      <div class="shrink" @click.stop="showAudio"><div class="arrow"></div></div>
      <div class="expand">
        <div class="cont">
          <div class="title">{{title}}</div>
          <audio id="myAudioPlayer" v-if="url" controlsList="nodownload" @pause="pause" @play="play" :loop="loop" :src="url"  preload="auto" ref="audioInstance" controls autoplay="autoplay">
<!--          <audio id="myAudioPlayer" @canplay="getDuration" v-if="url" controlsList="nodownload" :src="url"  preload="auto" ref="audioInstance" controls autoplay="autoplay">-->
        </audio>
        </div>
        <div class="ft" @click.stop="back">
          <div class="close">
            <i></i>
            <i></i>
          </div>
        </div>
      </div>
    </div>
    <readScore ref="scoreInstance" v-if="contentId && url" :key="contentId" :_contentId="contentId" :type="2"></readScore>
  </section>
</template>

<script>
import loginService from "@/service/loginService";
  let hasListen = false
  let playEndFn = null
  let timeupdateFn = null
  let broadcastId = ''
  export default {
    name: 'audioPlayer',
    props: ['id'],
    data () {
      return {
        currentIndex: 1,
        contentId: '',
        isShow: true,
        playing: !true,
        audioClass: '',
        instanceClass: 'out',
        title: '',
        url: '',
        detail: {},
        duration:0,//获取总时长
        scoreTime:0,
        loop:true,
      }
    },
    mounted () {
    },
    methods: {
      listenerEnd () {
        let myAudio = document.getElementById('myAudioPlayer')
        let me = this
        if (!myAudio) {
          return setTimeout(() => {
            this.listenerEnd()
          }, 100)
        }
        console.log('listenerEnd:', myAudio)
        myAudio.play()
        if (!timeupdateFn) {
          function timeupdate (e) {
            console.log('timeupdate')
            let myAudio = document.getElementById('myAudioPlayer')
            if (myAudio && myAudio.duration <= myAudio.currentTime + 0.5) {
              console.log('audio ended')
              console.log(e)
              me.onended()
            }
          }
          timeupdateFn = timeupdate
        }
        if (!playEndFn) {
          playEndFn = function () {
            me.onended()
          }
        }
        myAudio.removeEventListener('timeupdate', timeupdateFn)
        myAudio && myAudio.addEventListener('timeupdate', timeupdateFn)
        myAudio.removeEventListener('ended', playEndFn)
        myAudio && myAudio.addEventListener('ended', playEndFn)
      },

      /*设置完成听FM*/
      getScore () {
        clearTimeout(this.getScoreTimer)
        this.getScoreTimer = setTimeout(() => {
          if (!this.$refs.scoreInstance) {
            console.log('FM收听积分未完成')
            return this.getScore()
          }
          let nowTime = Date.now();
          if(nowTime - this.scoreTime < 1000){
            return false;
          }
          this.scoreTime = nowTime;
          this.$refs.scoreInstance.getScore('read')
        }, 100)
      },
      /*播放完成*/
      onended () {
        console.log('ended')
        this.playAudioNext()
        this.getScore()
      },
      /*播放下一首*/
      playAudioNext () {
        if (!this.$store.state.zhuanjiList) {
          return false
        }
        let audioList = this.$store.state.zhuanjiList
        console.log('playAudioNext')
        let playingIndex = audioList.findIndex(item => {
          return item.id === this.contentId
        })
        let nextIndex = playingIndex + 1
        if (nextIndex >= audioList.length) {
          nextIndex = 0
        }
        let nextData = audioList[nextIndex]
        let id = nextData.id
        this.fetchService.contentPageDetail(id).then(res => {
          if (res.code !== 0) {
            return false
          }
          let detail = res.data
          this.setContentId(nextData.id)
          this.setUrl(this.tools.getImgUrl(detail.files[0].fileId))
          this.setTitle(nextData.title)
          console.log('下一个FM:', nextData.title)
          setTimeout(() => {
            this.setVoice(1)
            this.listenerEnd()
          }, 100)
        })
      },
     /* getDuration() {
        console.log(this.$refs.audioInstance.duration); //此时可以获取到duration
        this.duration = this.$refs.audioInstance.duration;
        this.timer = setTimeout(() => {
        }, 3000)
      },*/
      /*播放语音播报相关的东西 title 标题 ,url 音频地址,type （true，false）是否需要调取获得积分接口*/
      playBroadcast (title,url,id,type) {
        this.loop = false
        let this_ = this
        if(url !== this.url){ //当请求不一样
          this.setUrl(url)
          this.setContentId(id)
          this.setTitle(title)
     /*     if(type){
            let params = {
              businessId: id,
              userId: this_.$localStorage.get('userInfo').id
            }
            loginService.contentRead(params).then(res=>{
              if(res.code == 0){
                console.log('提交成功')
              }
            })
          }*/
        }
        // this.setVoice(1)
        // this.play()
        this.instanceClass = ''
        setTimeout(() => {
          this.setVoice(1)
          // let myAudio = document.getElementById('myAudioPlayer')
          // myAudio.play()
          broadcastId = id;
          this.listenerEnd();
          this.$store.commit("setPLAY_BROADCAST",id);
        }, 100)
      },
      setContentId (id) {
        this.contentId = id
      },
      setUrl (url) {
        console.log('seturl')
        this.url = ''
        setTimeout(() => {
          this.url = url
          this.setVoice(0)
        }, 100)
      },
      setTitle (title) {
        this.title = title
      },
      showAudio () {
        this.audioClass = 'show-audio'
        this.hideAudio()
      },
      setVoice (num, time) {
        let nowTime = Date.now()
        time = time || nowTime
        if (nowTime - time > 3000) {
          return false
        }
        setTimeout(() => {
          if (!this.$refs.audioInstance) {
            console.log('播放器未初始化完成')
            return this.setVoice(num, time)
          }
          this.$refs.audioInstance.volume = num
        }, 100)
      },
      hideAudio () {
        setTimeout(() => {
          this.audioClass = ''
        }, 5000)
      },
      init () {
        this.isShow = true
        return this
      },
      show () {
        if (this.url.length > 0) {
          this.loop = true
          this.setVoice(1)
          this.play()
          this.instanceClass = ''
          this.listenerEnd()
        }
      },
      play () {
        // debugger

        this.$store.commit("setPLAY_BROADCAST", broadcastId);
        this.$refs.scoreInstance && this.$refs.scoreInstance.startRead()
        this.$refs.audioInstance && this.$refs.audioInstance.play()
//        if (this.$refs.audioInstance) {
//          this.$refs.audioInstance.currentTime = this.$store.state.audioCurrentTime
//        }
      },
      pause () {
        this.$store.commit("setPLAY_BROADCAST",'pause_'+this.$store.state.PLAY_BROADCAST);
        this.$refs.scoreInstance && this.$refs.scoreInstance.stopRead()
        this.$refs.audioInstance && this.$refs.audioInstance.pause()
      },
      hide () {
        this.instanceClass = 'out'
        this.pause()
      },
      back () {
        this.url = ''
        this.instanceClass = 'out'
      }
    }
  }
</script>

<style scoped lang="scss">
  @import "@/common/stylus/moon.scss";
  .audio-wrap {
    display:block;
    position:fixed;
    z-index:100;
    left:0;
    top:70%;
    transition:left .3s;
    &.out {
      left:-200vw;
    }
    .inner {
      position: relative;
      &.show-audio {
        .expand {
          left:0;
        }
        .shrink {
          display:none;
        }
      }
    }
  }
  .expand {
    max-width:100vw;
    width:90vw;
    transition:left .3s;
    left:-200vw;
    background: #230c32;
    text-align: center;
    padding:10px 20px;
    position: absolute;
    z-index:2;
    border-radius:0 10px 10px 0;
    display:flex;
    justify-content:space-between;
    align-items:center;
    padding-right:50px;
    .cont {
      padding-right:20px;
      flex:1;
      .title {
        max-width:100%;
        width:calc(90vw - 140px);
        flex:1;
        padding-bottom:5px;
        color:#fff;
        font-size:$titleFontSize;
        overflow: hidden;
        text-overflow: ellipsis;
        -webkit-line-clamp: 1;
        -webkit-box-orient: vertical;
        display:-webkit-box;
      }
      audio {
        width:calc(90vw - 140px);
      }
    }
    .ft {
      width: pxToRem(16px);
      flex-shrink:0;
    }
  }
  .shrink {
    background: #230c32;
    height:100px;
    width:50px;
    text-align: center;
    position: absolute;
    z-index:1;
    border-radius:0 10px 10px 0;
  }
  .arrow {
    position: absolute;
    top:50%;
    left:50%;
    transform:translate3d(-50%,-50%,0);
    display:inline-block;
    width: pxToRem(16px);
    height: pxToRem(25px);
    background:rgba(199,199,204,1);
    background: url("../../../static/images/dangjian/dangwu/arrow-left.png") no-repeat center;
    background-size: 100% auto;
  }
  .close {
    flex-shrink:0;
    width:pxToRem(30px);
    height:pxToRem(30px);
    position: relative;
    transform:rotate(45deg);
    i {
      background:#999;
      position: absolute;
    }
    i:first-child {
      top:50%;
      left:0;
      margin-top:-1px;
      width:pxToRem(30px);
      height:2px;
    }
    i:last-child {
      top:0;
      left:50%;
      margin-left:-1px;
      height:pxToRem(30px);
      width:2px;
    }
  }
</style>
